package cn.com.dashihui.web.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jfinal.aop.Duang;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;

import cn.com.dashihui.kit.CommonKit;
import cn.com.dashihui.kit.DatetimeKit;
import cn.com.dashihui.kit.DirKit;
import cn.com.dashihui.kit.ExcelExportUtil.Pair;
import cn.com.dashihui.web.base.BaseController;
import cn.com.dashihui.web.dao.Admin;
import cn.com.dashihui.web.dao.Category;
import cn.com.dashihui.web.dao.DetailsImg;
import cn.com.dashihui.web.dao.GoodsBaseImages;
import cn.com.dashihui.web.dao.GoodsEcard;
import cn.com.dashihui.web.dao.GoodsStoreRel;
import cn.com.dashihui.web.service.EcardGoodsService;
import cn.com.dashihui.web.service.StoreService;

/**
 * 平台基础商品管理，基础商品可由各分公司进行复制
 */
public class EcardGoodsController extends BaseController{
	private EcardGoodsService service = Duang.duang(EcardGoodsService.class);
	private StoreService storeService = new StoreService();
	/**
	 * 转到商品列表页面
	 */
	public void index(){
		List<Record> list=storeService.findAllSeller();
    	setAttr("list", list);
		render("index.jsp");
	}
	
	/**
	 * 列表页面异步请求数据
	 */
	public void page(){
		int pageNum = getParaToInt("pageNum", 0);
		if(pageNum==0){
			pageNum = getParaToInt(0, 1);
		}
		int pageSize = getParaToInt("pageSize", PropKit.getInt("constants.pageSize"));
 		int sGoodId = getParaToInt("sGoodId",0);
 		String sGoodName = getPara("sGoodName");
 		String sSellerId = getPara("sSellerId");
 		String sStoreId = getPara("sStoreId");
		int state = getParaToInt("sState",0);
		renderResult(0,service.findByPage(pageNum,pageSize,sGoodId,sGoodName,sSellerId,sStoreId,state));
	}
	//根据公司查询分公司
	public void chooseStore(){
		String[] sSellerId = getParaValues("sSellerId");
		System.out.println(sSellerId+"sSellerIdsSellerIdsSellerIdsSellerIdsSellerIdsSellerId");
		String str = java.lang.String.join("','", sSellerId);
		renderSuccess(storeService.chooseStore(str));
	}
	// 根据用户查询用户所属公司，根据公司sellerId关联分公司sellerId查询分公司
	public void chooseAllStore() {
		setAttr("storelist", storeService.chooseAllStore());	
		render("storeList.jsp");
	}

	/**
	 * 商品添加页面
	 */
	public void toAdd() {
		String LunBoNum = DatetimeKit.getFormatDate("yyyyMMddHHmmssSSS") + CommonKit.buildRandomNum(4);
		int userid = getCurrentUser().getInt("id");
		List<Category> oneCategories = service.finOneCategory();
		setAttr("oneCategories", oneCategories);
		setAttr("LunBoNum", LunBoNum);
		setAttr("userid", userid);
		render("add.jsp");
	}
	/**
	 * 图片列表
	 */
	public void imageIndex() {
		setAttr("LunBoNum", getPara(0));
		render("imageList.jsp");
	}
	/**
	 * 添加图片
	 */
	public void toImageAdd() {
		setAttr("LunBoNum", getPara(0));
		render("imageAdd.jsp");
	}
	/**
	 * 图文详情
	 */
	public void imgdetail() {
		UploadFile thumb = getFile();
		Map<String, Object> map = new HashMap<String, Object>();
		if (thumb != null) {
			String thumbFileName;
			String dir = DirKit.getDir(DirKit.GOODS_DETAIL);
			try {
				thumbFileName = uploadToFtp(dir, thumb);
				map.put("error", 0);
				map.put("url", PropKit.get("constants.ftppath").concat(dir).concat(thumbFileName));
				renderJson(map);
				return;
			} catch (IOException e) {
				e.printStackTrace();
				logger.debug("上传图片失败");
				map.put("error", 1);
				map.put("message", "图片上传失败");
				renderJson(map);
			}
		} else {
			map.put("error", 1);
			map.put("message", "图片为空");
			renderJson(map);
		}
	}
	/**
	 * 分公司产品文本编辑中图片上传
	 */
	public void uploadimg() {
		UploadFile thumb = getFile();
		Map<String, Object> map = new HashMap<String, Object>();
		if (thumb != null) {
			String thumbFileName;
			String dir = DirKit.getDir(DirKit.GOODS_DETAIL);
			try {
				thumbFileName = uploadToFtp(dir, thumb);
				map.put("error", 0);
				map.put("url", PropKit.get("constants.ftppath").concat(dir).concat(thumbFileName));
				renderJson(map);
				return;
			} catch (IOException e) {
				e.printStackTrace();
				logger.debug("上传图片失败");
				map.put("error", 1);
				map.put("message", "图片上传失败");
				renderJson(map);
			}
		} else {
			map.put("error", 1);
			map.put("message", "图片为空");
			renderJson(map);
		}
	}


	/**
	 * 图片分页
	 */
	public void imagePage() {
		renderSuccess(service.findAllImages(getPara(0)));
	}

	
	/**
	 * 删除图片
	 * 
	 * @return -1：删除失败，0：删除成功
	 */
	public void doImageDelete() {
		int id = getParaToInt(0, 0);
		if (id != 0 && service.delImage(id)) {
			renderSuccess();
			return;
		}
		renderFailed();
	}
	/**
	 * 添加详情图片列表
	 */
	public void imageDetailIndex() {
		setAttr("LunBoNum", getPara(0));
		render("detailImgList.jsp");
	}
	/**
	 * 详情图片分页
	 */
	public void imageDetailPage() {
		renderSuccess(service.findDetailImages(getPara(0)));
	}
	/**
	 * 添加详情图片页面
	 */
	public void toImageDetailAdd() {
		setAttr("LunBoNum", getPara(0));
		render("ImgDetailAdd.jsp");
	}
	/**
	 * 添加详情图片方法
	 * 
	 * @return -1：异常，0：成功，1：图片为空，2：图片上传失败
	 */
	public void doImageDetailAdd() {
		
		List<UploadFile> file = getFiles();
		logger.info(""+file.size());
		if (file.isEmpty()) {
			renderFailed("详情图片不能为空！");
			return;
		}else if (file.size() > 20) {
			renderFailed("详情图一次最多上传20张！");
			return;
		}
		// 保存
		String LunBoNum = getPara("LunBoNum");
		// 如果上传了图片，则上传至FTP，并记录图片文件名
		List<DetailsImg> fileList = new ArrayList<>();
		boolean isSuccess = false;
		for(int i=0; i<file.size(); i++) {
			UploadFile thumb = file.get(i);
			if (thumb != null) {
				String thumbFileName;
				String dir = DirKit.getDir(DirKit.GOODS_IMAGES);
				try {
					thumbFileName = uploadToFtp(dir, thumb);
				} catch (IOException e) {
					e.printStackTrace();
					renderResult(2);
					return;
				}
				DetailsImg image = new DetailsImg().set("LunBoNum", LunBoNum).set("thumb", dir.concat(thumbFileName));
				if (service.addDetailImage(image)) {
					fileList.add(image);
					isSuccess = true;
				}else {
					isSuccess = false;
				}
			} else {
				renderResult(1);
				return;
			}
		}
		if (isSuccess) {
			renderResult(0,fileList);
		} else {
			renderResult(1);
		}
	}
	/**
	 * 删除添加详情图片
	 * 
	 * @return -1：删除失败，0：删除成功
	 */
	public void doDetailImageDelete() {
		int id = getParaToInt(0, 0);
		if (id != 0 && service.delDetailImage(id)) {
			renderSuccess();
			return;
		}
		renderFailed();
	}
	/**
	 * 详情图片排序
	 */
	public void doDetailSort() {
		Map<String, String[]> params = getParaMap();
		if (params != null && params.size() != 0 && params.containsKey("sortKey")) {
			String sortKey = params.get("sortKey")[0];
			Map<String, String> sortMap = new HashMap<String, String>();
			for (String key : params.keySet()) {
				if (!key.equals("sortKey")) {
					String id = key.replace(sortKey, "");
					String no = params.get(key)[0];
					if (StrKit.isBlank(no) || no.length() > 3) {
						no = "0";
					}
					sortMap.put(id, no);
				}
			}
			service.sortDetailImages(sortMap);
			renderSuccess();
			return;
		}
		renderFailed();
	}
	/**
	 * 添加图片方法
	 * 
	 * @return -1：异常，0：成功，1：图片为空，2：图片上传失败
	 */
	public void doImageAdd() {
		List<UploadFile> file = getFiles("thumb");
		System.out.println("file"+file);
		System.out.println("file.size"+file.size());
		logger.info(""+file.size());
		if (file.isEmpty()) {
			renderFailed("轮播图片不能为空！");
			return;
		}else if (file.size() > 20) {
			renderFailed("轮播图一次最多上传20张！");
			return;
		}
		String LunBoNum = getPara("lunbonum");
		// 保存
		// 如果上传了图片，则上传至FTP，并记录图片文件名
		List<GoodsBaseImages> fileList = new ArrayList<>();
		
		boolean isSuccess = false;
		for(int i=0; i<file.size(); i++) {
			UploadFile thumb = file.get(i);
			System.out.println("thumb"+thumb);
			if (thumb != null) {
				String thumbFileName;
				String dir = DirKit.getDir(DirKit.GOODS_IMAGES);
				try {
					thumbFileName = uploadToFtp(dir, thumb);
				} catch (IOException e) {
					e.printStackTrace();
					renderResult(2);
					return;
				}
				GoodsBaseImages image = new GoodsBaseImages().set("LunBoNum", LunBoNum).set("thumb",
						dir.concat(thumbFileName));
				if (service.addImage(image)) {
					fileList.add(image);
					System.out.println("fileList"+fileList);
					isSuccess = true;
				}else {
					isSuccess = false;
				}
			} else {
				renderResult(1);
				return;
			}
		}
		if (isSuccess) {
			renderResult(0,fileList);
		} else {
			renderResult(1);
		}
	}
	/**
	 * 设置图片为商品LOGO
	 * 
	 * @return -1：异常，0：成功
	 */
	public void doSetImageLogo() {
		int id = getParaToInt(0, 0);
		int goodsid = getParaToInt("goodsid");
		if (id != 0 && service.setImageLogo(goodsid, id)) {
			renderSuccess();
			return;
		}
		renderFailed();
	}
	/**
	 * 图片排序
	 */
	public void doImageSort() {
		Map<String, String[]> params = getParaMap();
		if (params != null && params.size() != 0 && params.containsKey("sortKey")) {
			String sortKey = params.get("sortKey")[0];
			Map<String, String> sortMap = new HashMap<String, String>();
			for (String key : params.keySet()) {
				if (!key.equals("sortKey")) {
					String id = key.replace(sortKey, "");
					String no = params.get(key)[0];
					if (StrKit.isBlank(no) || no.length() > 3) {
						no = "0";
					}
					sortMap.put(id, no);
				}
			}
			service.sortImages(sortMap);
			renderSuccess();
			return;
		}
		renderFailed();
	}
	/**
	 * 添加商品
	 */
	public void doAdd() {
		// 商品主图
		UploadFile goodsthumb = getFile("goodsthumb");
		/* 商品基本信息 */
		// 商品名称
		String name = getPara("names");
		
		// 轮播图片和详情图片
		String LunBoNum = getPara("LunBoNum");
		// 所属类别：
		String categoryonid = getPara("categoryonid");
		String categorytwid = getPara("categorytwid");
		String categorythid = getPara("categorythid");
		String categoryfoid = getPara("categoryfoid");
		//市场价格
		String sellPrice = getPara("sellPrice");
		//市场价格
		String marketPrice = getPara("marketPrice");
		//商品库存
		String countnum = getPara("countnum");
		//商品货号
		String goodsNum=getPara("goodsNum");
		// 分公司id
		String[] storeids = getParaValues("checks");
		if (storeids == null) {
			renderResult(3);
			return;
		}
		//商品分公司关联
		String goodstore = DatetimeKit.getFormatDate("yyyyMMddHHmmssSSS") + CommonKit.buildRandomNum(4);
		for (int i = 0; i < storeids.length; i++) {
			GoodsStoreRel gsr = new GoodsStoreRel();
			String store = storeids[i];
			gsr.set("storeid", store).set("goodstore", goodstore).save();
		}
		// 添加分公司数
		int countStore = getParaToInt("storeid", 0);
		//是否赠送优惠
		int zsactivity = getParaToInt("zsactivity", 1);
		//优惠数量
		//积分值
		String zspointnum = getPara("zspointnum",null);
		//抵扣券
		String zsdedunum = getPara("zsdedunum",null);
		//优惠券
		String zscouponnum = getPara("zscouponnum",null);
		/* 商品详情 */
		// 文字简介
		String shortInfo = getPara("shortinfo");
		//备注
		String beizhu = getPara("beizhu");
		if (StrKit.isBlank(name)) {
			renderResult(1);
			return;
		} else if (StrKit.isBlank(categoryonid) || StrKit.isBlank(categorytwid) || StrKit.isBlank(categorythid) || StrKit.isBlank(categoryfoid)) {
			renderResult(2);
			return;
		} else if (StrKit.isBlank(marketPrice)) {
			renderResult(4);
			return;
		} else if (StrKit.isBlank(sellPrice)) {
			renderResult(6);
			return;
		} else if (goodsthumb == null) {
			renderResult(7);
			return;
		} else if (zsactivity == 2 && StrKit.isBlank(zspointnum) && StrKit.isBlank(zsdedunum) && StrKit.isBlank(zscouponnum)) {
			renderResult(16);
			return;
		} else {
//			GoodsEcard goods = new GoodsEcard();
			GoodsEcard goods = new GoodsEcard();
				goods.set("name", name)
					.set("LunBoNum", LunBoNum)
					.set("categoryonid", Integer.valueOf(categoryonid).intValue())
					.set("categorytwid", Integer.valueOf(categorytwid).intValue())
					.set("categorythid", Integer.valueOf(categorythid).intValue())
					.set("categoryfoid", Integer.valueOf(categoryfoid).intValue())
					.set("sellPrice", sellPrice)
					.set("marketPrice", marketPrice)
					.set("countnum", countnum)
					.set("goodsNum", goodsNum)
					.set("zsactivity", zsactivity)
					.set("zspointnum", zspointnum).set("zsdedunum", zsdedunum).set("zscouponnum", zscouponnum)
					.set("good_store", goodstore)
					.set("countStore", countStore)
					.set("state", 3)
					.set("createDate", DatetimeKit.getFormatDate("yyyy-MM-dd-HH-mm-ss"))
					.set("shortInfo", shortInfo)
					.set("beizhu", beizhu).set("goodsNum", goodsNum)
					;

			// 如果上传了图片，则上传至FTP，并记录图片文件名
			if (goodsthumb != null) {
				String thumbFileName;
				String dir = DirKit.getDir(DirKit.GOODS_BASE);
				try {
					thumbFileName = uploadToFtp(dir, goodsthumb);
				} catch (IOException e) {
					e.printStackTrace();
					renderResult(12);
					return;
				}
				goods.set("thumb", dir.concat(thumbFileName));
			}
			
			if (goods.save()) {
				renderSuccess();
			}
		}
		renderFailed();
	}
	
	/**
	 * 上架
	 */
	public void doUp() {
		String id = getPara("id");
		String createDate = DatetimeKit.getFormatDate("yyyy-MM-dd-HH-mm-ss");
		if (StrKit.isBlank(id)) {
			renderFailed("参数id不能为空");
			return;
		} else {
			int i = service.doUp(id, createDate);
			if (i == 1) {
				renderSuccess(service.findById(Integer.valueOf(id)));
				return;
			} else {
				// 3.其他情况
				renderFailed("下架失败");
				return;
			}
		}
	}
	/**
	 * 通过审核
	 */
	public void doAccept(){
		String id=getPara("id");
		String checktime=DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss");
		if(StrKit.isBlank(id)){
			renderFailed("参数id不能为空");
			return;
		}else{
			int i= service.doAccept(id,checktime);
			if(i==1){
				renderSuccess(service.findById(Integer.valueOf(id)));
				return ;
			}else{
				//3.其他情况
				renderFailed("审核失败");
				return;
			}
		}
	}
	/**
	 * 下架
	 */

	public void doDown() {
		String id = getPara("id");
		String downtime = DatetimeKit.getFormatDate("yyyy-MM-dd-hh-mm");
		// System.out.println(checktime);
		if (StrKit.isBlank(id)) {
			renderFailed("参数id不能为空");
			return;
		} else {
			int i = service.doDown(id, downtime);
			if (i == 1) {
				renderSuccess(service.findById(Integer.valueOf(id)));
				return;
			} else {
				// 3.其他情况
				renderFailed("下架失败");
				return;
			}
		}
	}
	 /**
	    * 驳回
	    */
	   public void toCancel(){
		   	String id=getPara("id");
		   	if(StrKit.isBlank(id)){
					renderFailed("id不能为空");
		   		return;
		   	}else{
		   		setAttr("id", id);
		   		render("doCancel.jsp"); 
		   	}
	   }
		 /**
	     * 驳回doCancel
	     */
	    public void doCancel(){
	    	String id=getPara("id");
	    	String reason=getPara("reason");
	    	String checktime=DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss");
	    	if(StrKit.isBlank(id)){
				renderFailed("参数id不能为空");
	    		return;
	    	}else{
	    		int i= service.doCancel(id,reason,checktime);
	    		if(i==1){
	    			renderSuccess(service.findById(Integer.valueOf(id)));
	    			return ;
	    		}else{
	    			//3.其他情况
					renderFailed("驳回失败");
					return;
	    		}
	    	}
	    }
	    /**
		 * 商品信息页面
		 */
		public void goodDetail() {
			int id = getParaToInt("id", 0);
			Admin admin = getCurrentUser();
			if ( admin == null ) {
				renderFailed();
			}
			int userid = admin.getInt("id");
			
			if (id != 0) {
				Record goods = service.findGoodDetailById(id);
				String gooditem = goods.getStr("goodItem");
				String good_store = goods.getStr("good_store");
				// String LunBoNum=goods.getStr("LunBoNum");
				if (!StrKit.isBlank(gooditem)) {
					List<Record> goodItem = service.getGoodsItem(gooditem);
					if (goodItem.size() > 0) {
						setAttr("goodItem", goodItem);
					}
				}
				if (!StrKit.isBlank(good_store)) {
					List<Record> store = service.getStore(good_store);
					if (store.size() > 0) {
						setAttr("store", store);
					}
				}
					List<Record> goodSpecs = service.getGoodSpec(id);
					if (goodSpecs.size() > 0) {
						setAttr("goodSpec", goodSpecs);
					}
				setAttr("goods", goods);
			}
			setAttr("userid", userid);
			List<Category> oneCategories = service.finOneCategory();
			setAttr("oneCategories", oneCategories);
			List<Category> twoCategories = service.findTwoCategory();
			setAttr("twoCategories", twoCategories);
			List<Category> threeCategories = service.findThreeCategory();
			setAttr("threeCategories", threeCategories);
			List<Category> fourCategories = service.findFourCategory();
			setAttr("fourCategories", fourCategories);
			render("detail.jsp");
		}

	    /**
	     * 删除商品
	     */
	    public void delete(){
	    	String id=getPara("id");
	    	if(StrKit.isBlank(id)){
				renderFailed("参数sellerId不能为空");
	    		return;
	    	}else{
	    		GoodsEcard goods=service.findById(Integer.valueOf(id));
	    		if(service.delete(goods)){
	    			renderSuccess();
	    			return ;
	    		}else{
	    			//3.其他情况
					renderFailed("删除失败");
					return;
	    		}
	    	}
	    }
	   
		//编辑商品时需要查询到四个等级的分类，根据商品的分类ID锁定当前商品的分类
		/**
		 * 二级分类
		 */
		public void categoryonid(){
			String[] categoryonid = getParaValues("categoryonid");
			String str = java.lang.String.join("','", categoryonid);
			renderSuccess(service.finTwoCategory(str));
		}
		/**
		 * 三级分类
		 */
		public void categorytwid(){
			String[] categorytwid = getParaValues("categorytwid");
			String str = java.lang.String.join("','", categorytwid);
			renderSuccess(service.finThreeCategory(str));
		}
		/**
		 * 四级分类
		 */
		public void categorythid(){
			String[] categorythid = getParaValues("categorythid");
			String str = java.lang.String.join("','", categorythid);
			renderSuccess(service.finFourCategory(str));
		}
		 /**
		 * 修改商品信息页面
		 */
		public void toEdit() {
			int id = getParaToInt(0, 0);
			int userid=getCurrentUser().getInt("id");
			if (id != 0) {
				Record goods = service.findGoodDetailById(id);
				String gooditem = goods.getStr("goodItem");
				String good_store = goods.getStr("good_store");
				// String LunBoNum=goods.getStr("LunBoNum");
				if (!StrKit.isBlank(gooditem)) {
					List<Record> goodItem = service.getGoodsItem(gooditem);
					if (goodItem.size() > 0) {
						setAttr("goodItem", goodItem);
					}
				}
				if (!StrKit.isBlank(good_store)) {
					List<Record> store = service.getStore(good_store);
					if (store.size() > 0) {
						setAttr("store", store);
					}
				}
				
					List<Record> goodSpecs = service.getGoodSpec(id);
					if (goodSpecs.size() > 0) {
						setAttr("goodSpecs", goodSpecs);
					}
				
				setAttr("goods", goods);

			}
			List<Category> oneCategories = service.finOneCategory();
			setAttr("oneCategories", oneCategories);
			List<Category> twoCategories = service.findTwoCategory();
			setAttr("twoCategories", twoCategories);
			List<Category> threeCategories = service.findThreeCategory();
			setAttr("threeCategories", threeCategories);
			List<Category> fourCategories = service.findFourCategory();
			setAttr("fourCategories", fourCategories);
			setAttr("userid", userid);
			render("edit.jsp");
		}
		/**
		 * 修改商品信息并保存
		 */
		public void doEdit() {
			/*
			 * 商品基本信息 由于不是同一张表，所以修改的操作是先把原始的数据删除掉 在进行重新的写入。
			 */
			// 商品主图
			UploadFile goodsthumb = getFile("goodsthumb");
			/* 商品基本信息 */
			// 商品名称
			String name = getPara("names");
			
			// 轮播图片和详情图片
			String LunBoNum = getPara("LunBoNum");
			// 所属类别：
			String categoryonid = getPara("categoryonid");
			String categorytwid = getPara("categorytwid");
			String categorythid = getPara("categorythid");
			String categoryfoid = getPara("categoryfoid");
			//市场价格
			String sellPrice = getPara("sellPrice");
			//市场价格
			String marketPrice = getPara("marketPrice");
			//商品库存
			String countnum = getPara("countnum");
			//商品货号
			String goodsNum=getPara("goodsNum");
			// 分公司id
			String[] storeids = getParaValues("checks");
			if (storeids == null) {
				renderResult(3);
				return;
			}
			int id = getParaToInt("id");
			Record good = service.findGoodDetailById(id);
			String goodstore = good.getStr("good_store");
			service.detelestore(goodstore);
			//商品分公司关联
			for (int i = 0; i < storeids.length; i++) {
				GoodsStoreRel gsr = new GoodsStoreRel();
				String store = storeids[i];
				gsr.set("storeid", store).set("goodstore", goodstore).save();
			}
			// 添加分公司数
			int countStore = getParaToInt("storeid", 0);
			//是否赠送优惠
			int zsactivity = getParaToInt("zsactivity", 1);
			//优惠数量
			//积分值
			String zspointnum = getPara("zspointnum",null);
			//抵扣券
			String zsdedunum = getPara("zsdedunum",null);
			//优惠券
			String zscouponnum = getPara("zscouponnum",null);
			/* 商品详情 */
			// 文字简介
			String shortInfo = getPara("shortinfo");
			//备注
			String beizhu = getPara("beizhu");
			String thumbOld = getPara("thumbOld");
			if (StrKit.isBlank(name)) {
				renderResult(1);
				return;
			} else if (StrKit.isBlank(categoryonid) || StrKit.isBlank(categorytwid) || StrKit.isBlank(categorythid) || StrKit.isBlank(categoryfoid)) {
				renderResult(2);
				return;
			} else if (StrKit.isBlank(marketPrice)) {
				renderResult(4);
				return;
			} else if (StrKit.isBlank(sellPrice)) {
				renderResult(6);
				return;
			} else if (goodsthumb == null) {
				renderResult(7);
				return;
			} else if (zsactivity == 2 && StrKit.isBlank(zspointnum) && StrKit.isBlank(zsdedunum) && StrKit.isBlank(zscouponnum)) {
				renderResult(16);
				return;
			} else {
				// GoodsEcard goods=new GoodsEcard()
				GoodsEcard goods = service.findByIdGoods(id)
						.set("name", name)
						.set("LunBoNum", LunBoNum)
						.set("categoryonid", Integer.valueOf(categoryonid).intValue())
						.set("categorytwid", Integer.valueOf(categorytwid).intValue())
						.set("categorythid", Integer.valueOf(categorythid).intValue())
						.set("categoryfoid", Integer.valueOf(categoryfoid).intValue())
						.set("good_store", goodstore)
						.set("sellPrice", sellPrice)
						.set("countStore", countStore)
						.set("state", 3)
						.set("createDate", DatetimeKit.getFormatDate("yyyy-MM-dd-HH-mm-ss"))
						.set("shortInfo", shortInfo)
						.set("pstate", 1)
						.set("beizhu", beizhu).set("goodsNum", goodsNum)
						.set("countnum", countnum)
						.set("zsactivity", zsactivity)
						.set("zspointnum", zspointnum).set("zsdedunum", zsdedunum).set("zscouponnum", zscouponnum)
						;
				// 如果上传了图片，则上传至FTP，并记录图片文件名
				if (goodsthumb != null) {
					String thumbFileName;
					String dir = DirKit.getDir(DirKit.GOODS_BASE);
					try {
						thumbFileName = uploadToFtp(dir, goodsthumb);
						deleteFromFtp(thumbOld);
					} catch (IOException e) {
						e.printStackTrace();
						renderResult(18);
						return;
					}
					goods.set("thumb", dir.concat(thumbFileName));
				}
				// 保存
				if (service.updategood(goods)) {
					//添加成功更新返回商品ID
					renderSuccess(service.findById(Integer.valueOf(id)));
					return;	
				}
			}
			renderFailed();
		}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	 
    
	
	
	
	
	

	

	

	
	
    
	
	
	
	/**
	 * excel导出
	 */
	public void doExcel(){
		List<Pair> titles = new ArrayList<Pair>();
	    titles.add(new Pair("id", "商品ID"));
	    titles.add(new Pair("name", "商品名称"));
	    
	    titles.add(new Pair("oneName", "商品类别"));
	    titles.add(new Pair("groupbuying", "商品属性"));
	    titles.add(new Pair("tState", "是否拓客"));
	    titles.add(new Pair("sellerName", "发布公司"));
	    titles.add(new Pair("createDate", "申请时间"));
	  /*  titles.add(new Pair("stock", "库存数量"));
	    titles.add(new Pair("type", "支付方式"));
	    titles.add(new Pair("paytype", "积分类型"));
	    titles.add(new Pair("sellpoint", "所需积分"));
	    titles.add(new Pair("sellPrice", "现金价格"));*/
	    titles.add(new Pair("countStore", "上架分公司数"));
	    titles.add(new Pair("checktime", "审核时间"));
	    titles.add(new Pair("downtime", "下架时间"));
	    titles.add(new Pair("pstate", "当前状态"));
 		int sGoodId = getParaToInt("sGoodId",0);
 		String sGoodName = getPara("sGoodName");
		String sSellerId = getPara("sSellerId");
		String sStoreId = getPara("sStoreId");
		int state = getParaToInt("sState",0);
		List<Record> list=service.findExcelByPage(sGoodId,sSellerId,sGoodName,sStoreId,state);
		List<Record> listz=new ArrayList<Record>();
		for (int i = 0; i < list.size(); i++) {
			Record record=new Record();
				record.set("id",list.get(i).get("id"));
				record.set("name", list.get(i).get("name"));
				record.set("oneName", list.get(i).get("oneName"));
				if(list.get(i).get("groupbuying").equals(1)){
					record.set("groupbuying", "常规");
				}else if(list.get(i).get("ftype").equals(2)){
					record.set("groupbuying", "团购");
				}
				if(list.get(i).get("tState")!=null&&list.get(i).get("tState").equals(1)){
					record.set("tState", "打开");
				}else {
					record.set("tState", "关闭");
				}
				record.set("sellerName", list.get(i).get("sellerName"));
				record.set("createDate", list.get(i).get("createDate"));
				/*record.set("stock", list.get(i).get("stock"));
				if(list.get(i).get("type").equals(1)){
					record.set("type", "货币");
				}else if(list.get(i).get("type").equals(2)){
					record.set("type", "积分");
				}else if(list.get(i).get("type").equals(3)){
					record.set("type", "货币积分");
				}
				if(list.get(i).get("paytype").equals(1)){
					record.set("paytype", "积分");
				}else if(list.get(i).get("paytype").equals(2)){
					record.set("paytype", "抵扣券");
				}else if(list.get(i).get("paytype").equals(3)){
					record.set("paytype", "惠券");
				}
				record.set("sellpoint", list.get(i).get("sellpoint"));
				record.set("sellPrice", list.get(i).get("sellPrice"));*/
				record.set("countStore", list.get(i).get("countStore"));
				record.set("checktime", list.get(i).get("checktime"));
				record.set("downtime", list.get(i).get("downtime"));
				if(list.get(i).get("pstate").equals(1)){
					if(list.get(i).get("state").equals(1)){
						record.set("pstate", "上架审核中");
					}else if(list.get(i).get("state").equals(2)){
						record.set("pstate", "上架");
					}else if(list.get(i).get("state").equals(3)){
						record.set("pstate", "下架");
					}
				}else if(list.get(i).get("pstate").equals(2)){
					record.set("pstate", "售罄");
				}else if (list.get(i).get("pstate").equals(3)){
					record.set("pstate", "降权");
				}
			listz.add(record);
 		}
		// 导出
		service.export(getResponse(), getRequest(),titles, listz);		
		renderNull();
	}
	
}
